import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import axios from 'axios'
import './plugins/element.js'
import { Message, Loading } from 'element-ui';
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import md5 from 'md5';

// md5
Vue.prototype.$md5 = md5

// markdown
Vue.use(mavonEditor)

Vue.config.productionTip = false
axios.defaults.withCredentials = true // 跨域
axios.defaults.baseURL = '/api'
// axios.defaults.headers.post['Content-Type'] = 'application/json'

// todo: 拦截器
// http request 请求拦截器
let loading
axios.interceptors.request.use(request => {
  loading = Loading.service({ fullscreen: true })
  request.headers.authorization = window.localStorage.getItem('token')
  return request
})

// http response 响应拦截器
axios.interceptors.response.use(response => {
  loading.close()
  if (response.status === 200) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(response)
  }
}, error => {
  loading.close()
    if (error.response.status) {
      // console.log(error.response);
    switch (error.response.status) {
      case 402:
        Message({
          type: 'error',
          message: '密码错误'
        });
        break;
      case 401:
        Message({
          type: 'error',
          message: error.response.data.msg
        });
        window.localStorage.clear()
        router.push('/login')
        break;
      case 403:
        Message({
          type: 'error',
          message: error.response.data.msg
        })
        break;
      case 301:
        Message({
          type: 'error',
          message: 'token过期'
        });
        window.localStorage.clear()
        router.push('/login')
        break;
      case 502:
        Message({
          type: 'error',
          message: '服务器错误'
        });
        break;
      default:
        // router.go(-1)
        Message({
          type: 'error',
          message: '错误'
        });
    }
  } else {
    Message({
      type: 'error',
      message: '连接服务器失败'
    });
    }
})

// 绑定axios
Vue.prototype.$http = axios

// 挂载过滤器
Vue.filter('formatDate', function (date) {
  const n = new Date(date)
  return n.getFullYear() + '-' + (n.getMonth() + 1) + '-' + n.getDate()
    + ' ' + n.getHours() + ':' + n.getMinutes() + ':' + n.getSeconds()
})

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')